package com.ysq.www.api.login.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysq.www.api.user.entity.User;
import com.ysq.www.api.user.service.IUserService;
import com.ysq.www.common.annotation.AuthToken;
import com.ysq.www.common.kit.ConstantKit;
import com.ysq.www.common.result.ResultMsg;
import com.ysq.www.common.utils.Comm;
import com.ysq.www.common.utils.RedisUtil;
import com.ysq.www.common.utils.h5.H5Utils;
import com.ysq.www.common.utils.token.Md5TokenGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IUserService userService;

    @Autowired
    private Md5TokenGenerator tokenGenerator;

    @PostMapping("/token")
    public ResultMsg login(HttpServletResponse response){
        //String pd = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        String username = Comm.getSysDate(2);
        String token = tokenGenerator.generate(username);
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.set(username, token);
        //设置key生存时间，当key过期时，它会被自动删除，时间是秒
        jedis.expire(username, ConstantKit.TOKEN_EXPIRE_TIME);
        jedis.set(token, username);
        jedis.expire(token, ConstantKit.TOKEN_EXPIRE_TIME);
        Long currentTime = System.currentTimeMillis();
        jedis.set(token + username, currentTime.toString());
        jedis.expire(token + username,ConstantKit.TOKEN_EXPIRE_TIME);
        //用完关闭
        jedis.close();
        response.setHeader("token",token);
        return ResultMsg.LOGIN_SUCCESS.setNewData(token);
    }


    /**
     * 静默授权登录
     * @param code 授权码
     * @param asId 协会id
     * @return ResultMsg
     */
    @GetMapping("/silentLogin")
    @AuthToken
    public ResultMsg silentLogin(String code,Integer asId){
        ResultMsg rm = userService.silentLogin(code,asId);
        return rm;
    }

}
